import { makeParams } from "@/utils/ruoyi";
import cache from "@/plugins/cache";
import { getToken, getUserInfo } from "@/utils/auth";
import { Notification, MessageBox, Message } from "element-ui";
import store from "@/store";
import errorCode from "@/utils/errorCode";
export const requestInterceptors = (axios, fn) => {
  axios.interceptors.request.use(
    (config) => {
      const { headers, method, params, url, data } = config;
      let needToken = true,
        needRepeatCheck = true;

      if (headers) {
        needToken = !(headers.needToken === false);
        needRepeatCheck = !(headers.needRepeatCheck === false);
      }

      if (getToken() && needToken) {
        config.headers["Authorization"] = "Bearer " + getToken();
      }
      // post请求增加默认参数
      if (needToken) {
        if (!config.params) {
          config.params = {};
        }
        let privateParams = fn();
        if (privateParams && privateParams.m) {
          Object.assign(config.params, privateParams);
        }
      }
      // get请求映射params参数
      if (method === "get" && params) {
        let getUrl = url + "?" + makeParams(params);
        getUrl = getUrl.slice(0, -1);
        config.params = {};
        config.url = getUrl;
      }

      if (needRepeatCheck && (method === "post" || method === "put")) {
        const requestObj = {
          url: url,
          data: typeof data === "object" ? JSON.stringify(data) : data,
          time: new Date().getTime(),
        };
        const isRepeat = isRepeatRequest(requestObj);
        if (isRepeat) {
          const message = "数据正在处理，请勿重复提交";
          console.warn(`[${url}]: ` + message);
          return Promise.reject(message);
        }
      }

      return config;
    },
    (error) => {
      console.log(error);
      Promise.reject(error);
    }
  );
};

export const responseInterceptors = (axios) => {
  axios.interceptors.response.use(
    (res) => {
      const code = res.data.code || 200;
      const msg = errorCode[code] || res.data.msg || errorCode["default"];
      if (
        res.request.responseType === "blob" ||
        res.request.responseType === "arraybuffer"
      ) {
        return res.data;
      }
      if (code === 401) {
        return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
      } else if (code === 500) {
        Message({ message: msg, type: "error" });
        return Promise.reject(new Error(msg));
      } else if (code === 601) {
        Message({ message: msg, type: "warning" });
        return Promise.reject("error");
      } else if (code !== 200) {
        Notification.error({ title: msg });
        return Promise.reject("error");
      } else {
        return res.data;
      }
    },
    (error) => {
      console.log("err" + error);
      let { message } = error;
      if (message == "Network Error") {
        message = "后端接口连接异常";
      } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
      } else if (message.includes("Request failed with status code")) {
        message = "系统接口" + message.substr(message.length - 3) + "异常";
      }
      Message({ message: message, type: "error", duration: 5 * 1000 });
      return Promise.reject(error);
    }
  );
};

const isRepeatRequest = (requestObj) => {
  const requestSize = Object.keys(JSON.stringify(requestObj)).length; // 请求数据大小
  const limitSize = 5 * 1024 * 1024; // 限制存放数据5M
  if (requestSize >= limitSize) {
    console.warn(
      `[${config.url}]: ` +
        "请求数据大小超出允许的5M限制，无法进行防重复提交验证。"
    );
    return false;
  }

  const sessionObj = cache.session.getJSON("sessionObj");
  if (sessionObj === undefined || sessionObj === null || sessionObj === "") {
    cache.session.setJSON("sessionObj", requestObj);
    return false;
  } else {
    const s_url = sessionObj.url; // 请求地址
    const s_data = sessionObj.data; // 请求数据
    const s_time = sessionObj.time; // 请求时间
    const interval = 1000; // 间隔时间(ms)，小于此时间视为重复提交
    if (
      s_data === requestObj.data &&
      requestObj.time - s_time < interval &&
      s_url === requestObj.url
    ) {
      return true;
    } else {
      cache.session.setJSON("sessionObj", requestObj);
      return false;
    }
  }
};
